<?php
/**
 * Created by PhpStorm.
 * User: dale
 * Date: 2017/12/18
 * Time: 下午2:27
 */

namespace Admin\Frontend\Controllers;

use Admin\Models\school\XhschoolInfo;
use Helpers\Cache;
use Helpers\HttpClient;
use Helpers\Main;
use Helpers\Tool;
use Helpers\User;
use Helpers\Assets;
use Helpers\Template;
use Admin\Models\stats\XhstatsBrushgroup;
use Admin\Models\stats\XhstatsBrushgroupuser;
use Admin\Models\sys\XhsysEnum;
use Helpers\UserPower;
use Helpers\XhException;
use Services\BigData;

class StatsBrushController extends ControllerBase
{
    /**
     * 古文刷题王
     *
     * create by dale 2017/12/18
     */
    public function chineseBrushAction(){
        $this -> view->disableLevel(\Phalcon\Mvc\View::LEVEL_MAIN_LAYOUT);
        $this->view->pick('stats_brush/chineseBrush');

        $now = date('Y-m-d',time());
        $this->view->setVars([
            'startDate' => $now,
            'endDate'   => $now,
            'time'      =>strtotime($now),
        ]);
    }

    public function searchAction(){
        $startDate = $this->request->getPost('startDate','string');
        $endDate   = $this->request->getPost('endDate','string');
        $schoolId  = $this->request->getPost('schoolId','int');
        if (!$startDate || !$endDate || !$schoolId){
            return $this->sendErrorResponse(400,'缺少参数');
        }
        $startDate  = strtotime($startDate . ' 00:00:00');
        $endDate    = strtotime($endDate . ' 23:59:59');
        $cacheKey = "chinese_brush_{$schoolId}_{$startDate}_{$endDate}";

        if (Cache::exists($cacheKey)) {
            $data = Cache::get($cacheKey);
            if (is_string($data)) {
                Cache::delete($cacheKey);
                return $this->sendErrorResponse(500, $data);
            }
        }else{
            return $this->sendErrorResponse(500,'没有生成缓存');
        }
        return $this->sendJsonResponse($data);
    }


    /**
     * 开启执行
     *
     * create by xjq 20180510
     * modify by ck 20180524    结构更改
     */
    public function startCacheBrushAction(){
        set_time_limit(0); //一直执行
        ignore_user_abort(true); //忽略程序被关闭
        $startDate = $this->request->getPost('startDate','string');
        $endDate   = $this->request->getPost('endDate','string');
        $schoolId  = $this->request->getPost('schoolId','int');
        $startDate  = strtotime($startDate . ' 00:00:00');
        $endDate    = strtotime($endDate . ' 23:59:59');
        if (!$startDate || !$endDate || !$schoolId){
            return $this->sendErrorResponse(500,'缺少必要参数');
        }
        if ($startDate > time()) {
            return $this->sendErrorResponse(400, '日期超出限制，不可查询');
        }
        if (($endDate - $startDate) > 2*3600 * 24 * 31){
            return $this->sendErrorResponse(400, '最多查询两个月数据');
        }
        $cacheKey = "chinese_brush_{$schoolId}_{$startDate}_{$endDate}";
        if (Cache::exists($cacheKey)) {
            return $this->sendSuccessResponse('缓存已存在，可直接使用');
        }
        $params = [
            'schoolId' => $schoolId,
            'startTime'=> $startDate,
            'endTime'  => $endDate,
        ];
        $url = Main::getConfigByName('stats_CA101004')['url'];
        $client   = new HttpClient($url);
        $response = $client->get('statistics/getClsStuInfo' , $params);
        if (!$response->isSuccess()){
            return $this->sendErrorResponse(500,$response->toArray()['msg'] ?:'错误',$response);
        }
        $data = $response->toArray();
//        $response = $client->setTimeout(3000)->get('statistics/getClsStuPractice' , $params);
//        if (!$response->isSuccess()){
//            return $this->sendErrorResponse(500,$response->toArray()['msg'] ?:'获取自练信息失败',$response);
//        }
//        $practice = $response->toArray();
//        $practice = array_column($practice,null,'iStuId');
//        foreach ($data as $index => &$row) {
//            foreach ($row['students'] as $key =>$value ) {
//                if(isset($practice[$value['stuId']])){
//                    $row['students'][$key]['pScore'] = $practice[$value['stuId']]['iScore']; //自练总成绩
//                    $row['students'][$key]['pNum'] = $practice[$value['stuId']]['useTime']; //自练篇数
//                }else{
//                    $row['students'][$key]['pScore'] = 0; //自练总成绩
//                    $row['students'][$key]['pNum']   = 0; //自练篇数
//                }
//
//            }
//        }
        if (!Cache::save($cacheKey , $data , 3600 * 12)) {
            return $this->sendErrorResponse(500,'缓存保存失败');
        }
        return $this->sendSuccessResponse('缓存保存成功');

    }

    /**
     * 检查缓存
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by xjq 20180510
     */
    public function checkBrushCacheAction(){
        $schoolId   = $this->request->getPost('schoolId', 'int');
        $startDate  = $this->request->getPost('startDate', 'string');
        $endDate    = $this->request->getPost('endDate', 'string');
        $startDate  = strtotime($startDate . ' 00:00:00');
        $endDate    = strtotime($endDate . ' 23:59:59');
        if (!$schoolId || !$startDate || !$endDate) {
            return $this->sendErrorResponse(400, '缺少必要参数', null, false);
        }
        $cacheKey = "chinese_brush_{$schoolId}_{$startDate}_{$endDate}";
        if (!Cache::exists($cacheKey)) {
            return $this->sendErrorResponse(500, '缓存未生成', null, false);
        }
        return $this->sendSuccessResponse('缓存存在，可查询');
    }




    /**
     * 初始化学生刷题信息列表
     *
     * create by dale 20180237
     */
    public function stuBrashInitAction(){

        $schoolIds = User::getSchoolPower(true,null,false);
        $startTime = date('Y-m-d',strtotime('-7 day'));
        $endTime   = date('Y-m-d',strtotime('-1 day'));

        try{
            $subject = $this->getBooksBySubject();
        }catch (XhException $e){
            return $this->sendErrorResponse(500 , $e->getMessage() ,$e->getDescription());
        }


        return $this->sendJsonResponse([
            'schoolIds' => $schoolIds,
            'startTime' => $startTime,
            'endTime'   => $endTime,
            'subject'   => $subject,
        ]);
    }

    /**
     * 获取书本信息
     *
     * @return array|\Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by dale 20180315
     */
    public function getBookAction(){
        try{
            $subjectId = $this->request->get('subjectId','int');
            if(!$subjectId){
                return $this->sendErrorResponse(400 , '缺少必要参数');
            }
            $book = $this->getBooksBySubject($subjectId , false);
            return $this->sendJsonResponse($book);
        }catch (XhException $e){
            return $this->sendErrorResponse(500 , $e->getMessage() ,$e->getDescription());
        }
    }

    /**
     * 获取书本通过学科
     * @param array $params
     * @param bool $json_encode
     * @return array|bool|mixed|\Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|\stdClass
     * @throws XhException
     * create by xjq 20180622
     */
    public function getBooksBySubject($subjectId = null, $json_encode = false)
    {

        $data = BigData::getBookBySubject($subjectId);
//        if ($subjectId) {
//            $data = $data['data'];
//        }
        if ($json_encode) {
            return $this->sendJsonResponse($data);
        } else {
            return $data;
        }
    }


    /**
     * 根据学校的id获取学校的班级
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by dale 20180237
     */
    public function getClassAction(){
        $schoolId = $this->request->getPost('schoolIds','int');
        if(!$schoolId){
            return $this->sendJsonResponse([]);
        }

        $url =  Main::getConfigByName('resServerInterface')['schoolBaseUrl'];
        $client   = new HttpClient($url);
        $response = $client->get('/api/v1/schools/'.$schoolId.'/classes/');
        if (!$response->isSuccess()){
            return $this->sendErrorResponse(500,$response->toArray()['msg'] ?:'调取接口失败',$response);
        }
        $arr = [];
        $data = $response->toArray();
        foreach ($data as $val){
            if(!$val['folder']){
                $arr[$val['id']] = $val['name'];
            }
        }
        return $this->sendJsonResponse($arr);

    }




    /**
     * 获取学生刷题信息统计列表
     *
     *
     * create by dale 20180237
     */
    public function getStuBrushAction(){
        $startTime = $this->request->getPost('startTime','string');
        $endTime   = $this->request->getPost('endTime','string');
        $schoolId  = $this->request->getPost('schoolId','string');
        $bookId    = $this->request->getPost('bookId');
        $classId   = $this->request->getPost('classId','string');
        if($schoolId == false){
            $schoolId = User::getSchoolPower(false,null,false);
            $schoolId = implode(',',$schoolId);
        }
        if($classId == false){
            $classId = [];
        }
        if (!is_array($bookId)) {
            $bookId = explode(',' , $bookId);
        }
//        $params = [
//            'schoolid'  => $schoolId,
//            'bookid'    => $bookId,
//            'starttime' => ,
//            'endedtime' => ,
//            'classid'   => $classId
//        ];
        try {
            $data = $this->getStuBrushList(
                $schoolId,
                strtotime($startTime.' 00:00:00'),
                strtotime($endTime.' 23:59:59'),
                $classId,
                $bookId
            );
            $arr = [];
            foreach ($data as $index => $rows){
                $item = [];
                $item['hp']          = $rows['hp'];
                $item['userId']      = $rows['userid'];
                $item['className']   = $rows['classname'];
                $item['rightCount']  = $rows['countright'];
                $item['countScore']  = $rows['countscore'];
                $item['timeCost']    = $rows['counttime'];
                $item['credit']      = $rows['credit'];
                $item['homeWorkNum'] = $rows['numhomework'];
                $item['selfWorkNum'] = $rows['numselfwork'];
                $item['rightRate']   = $rows['rightlv'];
                $item['topicNum']    = $rows['topicnum'];
                $item['userName']    = $rows['username'];
                $item['topicOld']    = $rows['topicold'];
                $item['integral']    = $rows['integral'];
                $arr[] = $item;
            }
            return $this->sendJsonResponse($arr);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
//        return $this->sendJsonResponse($params);
    }

    /**
     * 获取学生刷题王列表
     * @param $schoolId
     * @param $startTime
     * @param $endTime
     * @param array $classArr
     * @param array $bookArr
     *
     * @return array|bool|mixed|\stdClass|string
     * @throws XhException
     *
     * create by dale 20180315
     * modify by dale 20181022
     */
    public function getStuBrushList($schoolId,$startTime,$endTime,$classArr=[],$bookArr=[])
    {
//        $url = Main::getConfigByName('bigData')['url'];
//        $client   = new HttpClient($url);
//        $response = $client->postJson('bigdata/product_stw/getstwinfo',$params);
//        if (!$response->isSuccess()){
//            throw new \Exception($response->body ?:'调取接口失败');
//        }
        $data = BigData::getStuBrush($schoolId, $startTime, $endTime, $classArr, $bookArr);
//        $data = Tool::getValue($data, 'data', null);
        if (!$data) {
            throw new XhException('该班级在所选时间内暂无数据，请换个班级重试',$data);
        }
        return $data;
    }

    /**
     * 导出学生信息列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180238
     */
    public function exportStuExcelAction(){
        $this->view->disable();
        try{
            $startTime = $this->request->getQuery('startTime','string');
            $endTime   = $this->request->getQuery('endTime','string');
            $schoolId  = $this->request->getQuery('schoolId','string');
            $bookId    = $this->request->getQuery('bookId');
            $classId   = $this->request->getQuery('classId');
            $subType   = $this->request->getQuery('subType','string');
            if (!$subType || !$bookId) {
                return $this->sendErrorResponse(400 ,'subType必传或boolId必传');
            }
            if($schoolId == false){
                $schoolId = User::getSchoolPower(false,null,false);
                $schoolId = implode(',' , $schoolId);
            }
            if (!$bookId) {
                $bookId = [];
            }
            if (is_string($bookId)) {
                $bookId = explode(',' , $bookId);
            }
            if (!$classId) {
                $classId = [];
            }
            if (is_string($classId)) {
                $classId = explode(',', $classId);
            }


//            $params = [
//                'schoolid'  => $schoolId,
//                'bookid'    => $bookId,
//                'starttime' => strtotime($startTime.' 00:00:00'),
//                'endedtime' => strtotime($endTime.' 23:59:59'),
//                'classid'   => $classId
//            ];

            $data = $this->getStuBrushList(
                $schoolId,
                strtotime($startTime.' 00:00:00'),
                strtotime($endTime.' 23:59:59'),
                $classId,
                $bookId
            );

            $schoolName = XhschoolInfo::getSchoolArray()[$schoolId];
            $arr = [];
            foreach ($data as $index => $rows){
                $item = [];
                $item['hp']          = isset($rows['hp']) ? $rows['hp'] : '';
                $item['userId']      = $rows['userid'];
                $item['className']   = $rows['classname'];
                $item['rightCount']  = $rows['countright'];
                $item['countScore']  = $rows['countscore'];
                $item['timeCost']    = $rows['counttime'];
                $item['credit']      = isset($rows['credit']) ? $rows['credit'] : '';
                $item['homeWorkNum'] = $rows['numhomework'];
                $item['selfWorkNum'] = $rows['numselfwork'];
                $item['rightRate']   = $rows['rightlv'];
                $item['topicNum']    = $rows['topicnum'];
                $item['userName']    = $rows['username'];
                $item['schoolName']  = $schoolName;
                $item['topicOld']    = $rows['topicold'];
                $item['integral']    = $rows['integral'];
                $arr[] = $item;
            }
            if(in_array($subType , [1 , 3]) ){
                $title = [
                    'schoolName'=>'学校名称',
                    'userName' => '姓名',
                    'className' => '班级',
                    'hp' => '体力',
                    'credit' => '诚信分',
                    'countScore' => '积分',
                    'integral'   => '局得分',
                    'homeWorkNum' => '作业次数',
                    'selfWorkNum' => '自练次数',
                    'topicOld'    => '原始做题量',
                    'topicNum' => '做题量',
                    'rightCount' => '正确题数',
                    'rightRate'  => '正确率',
                    'timeCost' => '做题时间（秒）',
                ];
            } else {
                $title = [
                    'schoolName'=>'学校名称',
                    'userName' => '姓名',
                    'className' => '班级',
                    'hp' => '体力',
                    'credit' => '诚信分',
                    'countScore' => '积分',
                    'integral'   => '局得分',
                    'homeWorkNum' => '作业次数',
                    'selfWorkNum' => '自练次数',
                    'topicNum' => '做题量',
                    'rightCount' => '失败次数',
                    'rightRate'  => '正确率',
                    'timeCost' => '做题时间（秒）',
                ];
            }

            $data = [];
            foreach ($arr as $key => $row) {
                foreach ($title as $filed => $name) {
                    $data[$key][$filed] = isset($row[$filed]) ? $row[$filed] : '';
                }
            }
            Tool::exportExcelOnline('学海题舟'.$startTime.'至'.$endTime,$title,$data,'xlsx',['autoWidth'=>true,'header'=>['title'=>'刷题王学生信息统计（'.$startTime.'-'.$endTime.'）']]);
        }catch (\Exception $e){
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }


    /**********************************
     * 刷题王学校学生分组及查看分组达标情况
     * create by ck
     **********************************/

    public static $brushGroupEnum = [
        'sSubject' => ['数学' => '数学', '科学' => '科学', '英语' => '英语']
    ];

    /**
     * 刷题分组及学生列表页面
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20180322
     */
    public function brushGroupAction()
    {
        $schoolId = $this->request->getQuery('schoolId', 'int');
        if (!$schoolId) {
            return $this->sendViewError('缺少学校id');
        }
        if (!UserPower::checkUserPower('School_List_BrushGroup')) {
            return $this->sendViewError('缺少权限');
        }
        $this->view->pick('stats_brush/brushGroup');
        Assets::easyUI('js/stats_brush/brushGroup.js');
        $groupButtonArr = $studSearchArr = $studButtonArr = [];
        if (UserPower::checkUserPower('School_List_BrushGroup_Add')) {
            $groupButtonArr[] = ['id'=>'bt_group_add', 'text' => '新增', 'icon'=>'fa-plus', 'class' => 'easyui-linkbutton'];
            $studButtonArr[]  = ['id'=>'bt_stud_add', 'text' => '新增', 'icon'=>'fa-plus'];
        }
        if (UserPower::checkUserPower('School_List_BrushGroup_Del')) {
            $groupButtonArr[] = ['id'=>'bt_group_del', 'text' => '删除', 'icon'=>'fa-trash', 'class' => 'easyui-linkbutton'];
            $studButtonArr[]  = ['id'=>'bt_stud_del', 'text' => '删除', 'icon'=>'fa-trash'];
        }
        return $this->view->setVars([
            'GroupList' => Template::createList('group_list', 'Stats_BrushGroup', [
                'checkbox'      => false,
                'buttonToolbar' => Template::createButtonToolBar($groupButtonArr)
            ]),
            'List' => Template::createList('list', 'Stats_BrushGroupUser', [
                'buttonToolbar' => Template::createButtonToolBar($studButtonArr)
            ])
        ]);
    }

    /**
     * 获取班级/分组列表（根据是否有id）
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180320
     */
    public function getClassBrushGroupAction()
    {
        $schoolId = $this->request->getPost('schoolId', 'int');
        $classId  = $this->request->getPost('id', 'string');
        if (!$schoolId) {
            return $this->sendErrorResponse(400, '缺少学校id');
        }
        if (!$classId) {
            $httpClient = new HttpClient(Main::getConfigByName('user')['url']);
            $response   = $httpClient->get(sprintf('/api/v1/schools/%d/classes/', $schoolId));
            if (!$response->isSuccess()) {
                return $this->sendErrorResponse(500, '班级获取失败', $response);
            }
            $data = [];
            foreach ($response->toArray() as $row) {
                if ($row['folder']) {
                    continue;
                }
                $data[] = [
                    'id'        => $row['id'],
                    'targetId'  => $row['id'],
                    'name'      => $row['name'],
                    'target'    => 'class',
                    'state'     => 'closed'
                ];
            }
        }
        else {
            try {
                $groups = XhstatsBrushgroup::find([
//                    'columns' => 'id,sGroupName AS name,sSubject AS subject',
                    'conditions' => 'bDelete = 0 AND sClassId = :classId:',
                    'bind'       => ['classId' => $classId]
                ])->toArray();
                $data = [];
                foreach ($groups as $row) {
                    $subject = $row['sSubject'];
                    if (!isset($data[$subject])) {
                        $data[$subject] = [
                            'id'     => $classId . '_' . $subject,
                            'name'   => $subject,
                            'target' => 'subject'
                        ];
                    }
//                    $standard = unserialize($row['mStandard']);
                    $data[$subject]['children'][] = [
                        'id'        => $classId . '_' . $row['id'],
//                        'name'      => $row['sGroupName'] . "&nbsp;&nbsp;<font class='tip'>{$row['iTopicExecStandard']}题({$row['iTopicExecUpStandard']}题↑&nbsp;{$row['iTopicExecDownStandard']}题↓)&nbsp;&nbsp;{$row['iRightRateStandard']}%({$row['iRightRateUpStandard']}%↑&nbsp;{$row['iRightRateDownStandard']}%↓)</font>",
                        'name'      => $row['sGroupName'],
                        'target'    => 'group',
                        'targetId'  => $row['id']
                    ];
                }
                $data = array_values($data);
            } catch (\Exception $e) {
                return $this->sendErrorResponse(500, $e->getMessage());
            }
        }
        return $this->sendJsonResponse($data);
    }

    /**
     * 获取组内外学生列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180321
     * modify by ck 20180322
     */
    public function getBrushGroupUserAction()
    {
        $schoolId = $this->request->getPost('schoolId', 'int');
        $classId  = $this->request->getPost('classId', 'string');
        $groupId  = $this->request->getPost('groupId', 'int');
        $out      = $this->request->getPost('type', 'string') == 'out';
        if (!$groupId) {
//            return $this->sendJsonResponse([]);
            return $this->sendDataGridError('缺少组id', null, false);
        }
        try {
            $builder = $this->modelsManager->createBuilder()
                ->columns(['u.iUserId', 'u.sUserName', 'u.sLogonName'])
                ->from(['gu' => '\\Admin\\Models\\stats\\XhstatsBrushgroupuser'])
//                ->where('u.bDelete = 0 AND u.bDisable = 0 AND u.bCompany = 0 AND u.bHistory = 0');
                ->where('u.bDelete = 0 AND u.bDisable = 0 AND u.bHistory = 0');
            if (!$out) {
                $builder->columns(array_merge(['gu.id', 'gu.tCreateDate'], $builder->getColumns()))
                    ->leftJoin('\\Admin\\Models\\user\\XhsysUser', 'gu.iUserId = u.iUserId', 'u')
                    ->andWhere('gu.bDelete = 0 AND gu.iGroupId = :id:', ['id' => $groupId]);
            }
            else {
                $httpClient = new HttpClient(Main::getConfigByName('user')['url']);
                $response   = $httpClient->get(sprintf('api/v1/schools/%d/classes/%d/members/', $schoolId, $classId), ['fields' => 'id']);
                if (!$response->isSuccess()) {
                    return $this->sendErrorResponse(500, '学生获取失败', $response);
                }
                $studIds = [];
                foreach ($response->toArray() as $row) {
                    $studIds[] = $row['id'];
                }
                if (!$studIds) {
                    return $this->sendErrorResponse(400, '该班级无学生');
                }
                //获取该组该科目下所有组id
                $subject  = XhstatsBrushgroup::findFirst($groupId)->sSubject;
                $groupIds = XhstatsBrushgroup::find([
                    'columns' => 'id',
                    'conditions' => 'bDelete = 0 AND sClassId = :classId: AND sSubject = :subject:',
                    'bind'       => ['classId' => $classId, 'subject' => $subject]
                ])->toArray();
                $groupIds = array_column($groupIds, 'id');
                $builder->rightJoin('\\Admin\\Models\\user\\XhsysUser', 'gu.iUserId = u.iUserId AND gu.bDelete = 0 AND gu.iGroupId IN (' . implode(',', $groupIds) . ')', 'u')
                    ->inWhere('u.iUserId', $studIds)
                    ->andWhere('gu.id IS NULL');
            }
            return $this->sendJsonResponse(Main::runBuilderPage($builder));
        }
        catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 刷题组添加/修改页面
     *
     * @return \Phalcon\Mvc\View
     *
     * create by ck 20180321
     */
    public function brushGroupFormAction()
    {
        $groupId = $this->request->getQuery('groupId', 'int');
        if (!UserPower::checkUserPower($groupId ? 'School_List_BrushGroup_Edit' : 'School_List_BrushGroup_Add')) {
            return $this->sendViewError('无该权限，不可操作');
        }
        $this->view->pick('stats_brush/brushGroupForm');
        Assets::importJs('js/stats_brush/brushGroupForm.js');
//        $subjectEnum = [];
//        foreach (XhsysEnum::getEnumByNodeName('学科') as $subject) {
//            $subjectEnum[$subject] = $subject;
//        }
        $obj = $groupId ? XhstatsBrushgroup::findFirst($groupId)->toArray() : false;
        if ($obj) {
            $standard = XhstatsBrushgroup::standardToString($obj['mStandard']);
            unset($obj['mStandard']);
            $obj = array_merge($obj, $standard);
        }
        return $this->view->setVars([
            'Form'  => Template::createForm('Stats_BrushGroup', self::$brushGroupEnum),
            'obj'   => $obj
        ]);
    }

    /**
     * 保存刷题分组
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180320
     */
    public function saveBrushGroupAction()
    {
        $id  = $this->request->getPost('id', 'int');
        try {
            $obj = $id ? XhstatsBrushgroup::findFirst($id) : new XhstatsBrushgroup();
            $obj->assign($this->request->getPost());
            if (!$obj->save()) {
                throw new \Exception($obj->getError());
            }
            return $this->sendSuccessResponse('保存成功');
        }
        catch (\Exception $e) {
            return $this->sendErrorResponse(500, '保存失败', $e->getMessage());
        }
    }

    /**
     * 删除刷题王分组
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180322
     */
    public function delBrushGroupAction()
    {
        $ids = $this->request->getPost('ids', 'int');
        if (!$ids) {
            return $this->sendErrorResponse(400, '缺少id');
        }
        if (!XhstatsBrushgroup::deleteRecord('id', $ids)) {
            return $this->sendErrorResponse(500, '删除失败');
        }
        return $this->sendSuccessResponse('删除成功');
    }

    /**
     * 刷题组用户增加页面
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20180322
     */
    public function brushGroupUserAddAction()
    {
        $schoolId = $this->request->getQuery('schoolId', 'int');
        $classId  = $this->request->getQuery('classId', 'string');
        $groupId  = $this->request->getQuery('groupId', 'int');
        if (!$schoolId || !$classId || !$groupId) {
            return $this->sendViewError('缺少必要参数');
        }
        $this->view->setTemplateBefore('listForm');
        Assets::easyUI('js/stats_brush/brushGroupUserAdd.js');
        return $this->view->setVars([
            'List' => Template::createList('list', 'Stats_BrushGroupUserAdd')
        ]);
    }

    /**
     * 添加用户到刷题组
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180322
     */
    public function addBrushGroupUserAction()
    {
        $groupId  = $this->request->getPost('groupId', 'int');
        $studIds  = $this->request->getPost('studId', 'int');
        if (!$groupId) {
            return $this->sendErrorResponse(400, '缺少组id');
        }
        if (!$studIds) {
            return $this->sendErrorResponse(400, '缺少学生id');
        }
        try {
            $this->db->begin();
            foreach ($studIds as $studId) {
                $obj = new XhstatsBrushgroupuser();
                $obj->iGroupId = $groupId;
                $obj->iUserId  = $studId;
                if (!$obj->save()) {
                    throw new \Exception($obj->getError());
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('保存成功');
        }
        catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, '保存失败', $e->getMessage());
        }
    }

    /**
     * 用户组删除用户
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180322
     */
    public function delBrushGroupUserAction()
    {
        $ids = $this->request->getPost('ids', 'int');
        if (!$ids) {
            return $this->sendErrorResponse(400, '缺少id');
        }
        if (!XhstatsBrushgroupuser::deleteRecord('id', $ids)) {
            return $this->sendErrorResponse(500, '删除失败');
        }
        return $this->sendSuccessResponse('删除成功');
    }

    /**
     * 检查刷题王分组是否完毕
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180328
     */
    public function checkBrushGroupStatusAction()
    {
        $schoolId = $this->request->getPost('schoolId', 'int');
        if (!$schoolId) {
            return $this->sendErrorResponse(400, '缺少学校id');
        }
        $httpClient = new HttpClient(Main::getConfigByName('user')['url']);
        $response   = $httpClient->get(sprintf('/api/v1/schools/%d/classes/', $schoolId));
        if (!$response->isSuccess()) {
            return $this->sendErrorResponse(500, '班级获取失败', $response);
        }
        $classIds = [];
        foreach ($response->toArray() as $row) {
            if ($row['folder']) {
                continue;
            }
            $classIds[] = $row['id'];
        }
        if (!$classIds) {
            return $this->sendJsonResponse(['classNum' => 0, 'groupClass' => 0]);
        }
        try {
            //对比数据库是否都已分组
            $count = XhstatsBrushgroup::findFirst([
                'columns'    => 'count(distinct(sClassId)) AS count',
                'conditions' => 'bDelete = 0 AND iSchoolId = :schoolId: AND sClassId IN ({classIds:array})',
                'bind'       => ['schoolId' => $schoolId, 'classIds' => $classIds]
            ])->toArray()['count'];
            return $this->sendJsonResponse(['classNum' => count($classIds), 'groupClass' => $count]);
        }
        catch (\Exception $e) {
            return $this->sendErrorResponse(500, '获取失败', $e->getMessage());
        }
    }

}